from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import base64
import ddddocr

from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.options import Options as FirefoxOptions


def download_and_process_file(url, driver, original_window):
    # 获取当前窗口句柄
    current_window = driver.current_window_handle

    # 使用 JavaScript 打开一个新标签页
    driver.execute_script("window.open('');")

    # 等待新标签页打开并获取所有窗口句柄
    WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)
    all_windows = driver.window_handles

    # 切换到新标签页
    for window in all_windows:
        if window != current_window:
            driver.switch_to.window(window)
            break

    # 在新标签页中访问 URL
    driver.get(url)

    try:
        # 等待页面加载和验证码处理逻辑（与之前相同）
        wait = WebDriverWait(driver, 20)
        link = wait.until(EC.visibility_of_element_located((By.XPATH, '//table/tbody//a[1]')))

        link.click()
        time.sleep(5)

        captcha_element = wait.until(EC.visibility_of_element_located((By.XPATH, '//img[@class="verifyCode"]')))
        driver.execute_script("arguments[0].scrollIntoView();", captcha_element)

        captcha_base64 = captcha_element.screenshot_as_base64
        with open('captcha_from_base64.png', 'wb') as f:
            f.write(base64.b64decode(captcha_base64))

        ocr = ddddocr.DdddOcr()
        captcha_image_bytes = base64.b64decode(captcha_base64)
        code = ocr.classification(captcha_image_bytes)

        print("验证码：", code)

        captcha_input = driver.find_element(By.ID, 'verifyCode')
        captcha_input.send_keys(code)
        time.sleep(1)

        submit_button = driver.find_element(By.XPATH, '//button[@class="btn btn-primary" and text()="验证"]')
        submit_button.click()
        time.sleep(15)
        current_url = driver.current_url

        if current_url == "about:blank":
            # 切换到原始标签页并打印错误消息（或执行其他错误处理逻辑）
            driver.switch_to.window(original_window)  # 确保 original_window 是在之前定义的
            print("验证码错误，页面停留在 about:blank")
            # 这里可以添加重新尝试验证码的逻辑，或者简单地跳过当前 URL
            return

    except Exception as e:
        print(f'处理 URL {url} 时出错: {e}')
    finally:
        # 关闭当前标签页（即新打开的标签页），回到原始标签页（如果尚未切换回去）
        if driver.current_window_handle != original_window:  # 确保不会关闭原始标签页
            driver.close()
            driver.switch_to.window(original_window)


def process_urls_from_file(output_file):
    options = Options()
    options.headless = True  # 根据需要设置为 True 或 False
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)

    try:
        with open(output_file, 'r', encoding='utf-8') as file:
            original_window = driver.current_window_handle  # 保存原始标签页的句柄
            i = 1
            for line in file:
                url = line.strip()
                if url:
                    print(f"第{i}个 URL: {url}")
                    download_and_process_file(url, driver, original_window)
                    i += 1
                    if i > 20:
                        break
    except FileNotFoundError:
        print(f"Error: The file {output_file} was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # 确保 WebDriver 在完成后被关闭
        driver.quit()


def main():
    output_file = 'detail_urls.txt'
    process_urls_from_file(output_file)


if __name__ == '__main__':
    main()
